#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<cstdlib>
#include<unistd.h>
#include<string>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
#include<strings.h>
#include<string.h>
#include"Terminal.hpp"
using namespace std;

void Usage(std::string proc)
{
    std::cout<<"\n\rUsage"<<proc<<"serverip  serverport\n"<<std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void* recv_message(void* args)
{
    //OpenTerminal();
    ThreadData* td = static_cast<ThreadData*>(args);
    char buffer[1024];
    while(true)
    {
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        ssize_t s = recvfrom(td->sockfd,buffer,1023,0,(struct sockaddr*)&tmp,&len);

        if(s > 0)
        {
            buffer[s] = 0; 
            std::cerr<<buffer<<std::endl;
        }
    }
}
void* send_message(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    socklen_t len = sizeof(td->server);
    std::string message;

    std::string welcome = td->serverip;
    welcome += "comming";
    sendto(td->sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&(td->server),len);

    while(true)
    {
        std::cout<<"Please Enter";
        getline(cin,message);
        std::cout<<message<<std::endl;
    
        sendto(td->sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&(td->server),len);
    }
}
//多线程
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct ThreadData td;
    bzero(&td.server,sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());
    

    td.sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(td.sockfd < 0)
    {
        std::cout<<"socket error"<<std::endl;
        return 1;
    }

    char buffer[1024];
    std::string message;

    td.serverip = serverip;

    pthread_t recvr,sender;
    pthread_create(&recvr,nullptr,recv_message,&td);
    pthread_create(&sender,nullptr,send_message,&td);
    pthread_join(recvr,nullptr);
    pthread_join(sender,nullptr);


    // while(true)
    // {

    //     std::cout<<"Please Enter";

    //     getline(cin,message);
    //     std::cout<<message<<std::endl;

    //     sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&server,len);

    //     struct sockaddr_in tmp;
    //     socklen_t len = sizeof(tmp);
    //     ssize_t s = recvfrom(sockfd,buffer,1023,0,(struct sockaddr*)&tmp,&len);

    //     if(s > 0)
    //     {
    //         buffer[s] = 0; 
    //         std::cout<<buffer<<std::endl;
    //     }
    // }  

    close(td.sockfd);

    return 0;
}